package com.tianx.util;

import javax.swing.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 工厂专用Util
 */
public class FactoryUtil {

    /**
     * 将字符串的首字母大写
     *
     * @param s 目标字符串
     * @return 首字母大写后的字符串
     */
    public static String capitalize(String s) {
        char[] chars = s.toCharArray();
        if ('a' <= chars[0] && chars[0] <= 'z')
            chars[0] = (char) (chars[0] - 'a' + 'A');
        return new String(chars);
    }

    /**
     * 将Class转换为包装类
     *
     * @param c 目标Class
     * @return 被包装类转化后的Class
     */
    public static Class<?> transform(Class<?> c) {
        switch (c.getTypeName()) {
            case "byte":
                return Byte.class;
            case "short":
                return Short.class;
            case "int":
                return Integer.class;
            case "long":
                return Long.class;
            case "float":
                return Float.class;
            case "double":
                return Double.class;
            case "char":
                return Character.class;
            case "boolean":
                return Boolean.class;
            default:
                return c;
        }
    }

    /**
     * 查询map中的字段
     * @param map 目标map
     * @param type 目标字段
     * @return 包含于map中的字段
     */
    public static Field getFieldByName(Map<Field, String> map, String type) {
        for (Field field : map.keySet()) {
            if (map.get(field).equals(type))
                return field;
        }
        return null;
    }

    /**
     * 获取对象的值的对话框
     * @param field 目标字段
     * @param value 目标值
     * @param title 对话框标题
     * @return 获得的值
     */
    public static Object getValueDialog(Field field, String value, String title) {
        String res = JOptionPane.showInputDialog(null,
                "输入" + value,
                title,
                JOptionPane.PLAIN_MESSAGE);
        if (res == null) return null;
        try {
            return transform(field.getType()).getConstructor(String.class).newInstance(res);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        } catch (InvocationTargetException e) {
            return null;
        }
    }
}
